package com.example.demo;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter{

	@Bean
	public UserDetailsService userDetailsService(){
		InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
		manager.createUser(User.withUsername("user").password("password").roles("USER").build());
		return manager;
	}
	
	protected void configure(HttpSecurity http) throws Exception {
		http
			//Header control
		.headers()
			.cacheControl()
				.and()
			.and()
			//disable csrf
			.csrf()
				.disable();
			
			http
			//访问控制
			//访问资源，不需要登录
			//要访问/admin下的资源，必须具有admin角色
			//访问其它资源，必须具有user角色
			.authorizeRequests()
				.antMatchers("/resources/**").permitAll()
				.antMatchers("/admin/**").hasRole("ADMIN")
				.antMatchers("/**")
					.hasRole("USER")
					.and()
					.formLogin();
				
	}
}
